package com.yunxin.utils.http;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Http {

    public static class HttpResponse<T> {
        public int responseCode;
        public String responseMessage;
        public Map<String, List<String>> headerFields;
        public T responseBody;
    }


    public static HttpResponse<byte[]> postForBytes(String url, String data, String... headers) throws Throwable {
        URL realurl = null;
        InputStream in = null;
        HttpURLConnection conn = null;
        HttpResponse httpResponse = new HttpResponse();

        Map<String, String> header = new HashMap();
        for (int i = 0; i < headers.length; i += 2) {
            header.put(headers[i], headers[i + 1]);
        }
        realurl = new URL(url);
        conn = (HttpURLConnection) realurl.openConnection();
        conn.setConnectTimeout(8000);
        conn.setReadTimeout(8000);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setAllowUserInteraction(true);
        for (String key : header.keySet()) {
            conn.setRequestProperty(key, header.get(key));
        }
        conn.setRequestMethod("POST");
        PrintWriter pw = new PrintWriter(conn.getOutputStream());
        pw.print(data);
        pw.flush();
        pw.close();
        httpResponse.responseCode = conn.getResponseCode();
        httpResponse.responseMessage = conn.getResponseMessage();
        httpResponse.headerFields = conn.getHeaderFields();
        in = conn.getInputStream();
        httpResponse.responseBody = streamToBytes(in);
        return httpResponse;
    }

    public static HttpResponse<byte[]> getForBytes(String url, String... headers) throws Throwable {
        URL realurl = null;
        InputStream in = null;
        HttpURLConnection conn = null;
        HttpResponse httpResponse = null;

        Map<String, String> header = new HashMap<>();
        for (int i = 0; i < headers.length; i = i + 2) {
            header.put(headers[i], headers[i + 1]);
        }
        realurl = new URL(url);
        conn = (HttpURLConnection) realurl.openConnection();
        conn.setConnectTimeout(8000);// 8秒
        conn.setReadTimeout(8000);// 8秒
        conn.setUseCaches(false);//不能使用缓存
        conn.setRequestMethod("GET");
        for (String key : header.keySet()) {
            conn.setRequestProperty(key, header.get(key));
        }
        httpResponse = new HttpResponse();
        httpResponse.responseCode = conn.getResponseCode();
        httpResponse.responseMessage = conn.getResponseMessage();
        httpResponse.headerFields = conn.getHeaderFields();
        in = conn.getInputStream();
        httpResponse.responseBody = streamToBytes(in);
        return httpResponse;
    }


    public static HttpResponse<String> post(String url, String data, String... headers) throws Throwable {
        URL realurl = null;
        InputStream in = null;
        HttpURLConnection conn = null;
        HttpResponse httpResponse = new HttpResponse();

        Map<String, String> header = new HashMap();
        for (int i = 0; i < headers.length; i += 2) {
            header.put(headers[i], headers[i + 1]);
        }
        realurl = new URL(url);
        conn = (HttpURLConnection) realurl.openConnection();
        conn.setConnectTimeout(8000);
        conn.setReadTimeout(8000);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setAllowUserInteraction(true);
        for (String key : header.keySet()) {
            conn.setRequestProperty(key, header.get(key));
        }
        conn.setRequestMethod("POST");
        PrintWriter pw = new PrintWriter(conn.getOutputStream());
        pw.print(data);
        pw.flush();
        pw.close();
        httpResponse.responseCode = conn.getResponseCode();
        httpResponse.responseMessage = conn.getResponseMessage();
        httpResponse.headerFields = conn.getHeaderFields();
        in = conn.getInputStream();

        httpResponse.responseBody = streamToString(in);
        return httpResponse;
    }

    public static HttpResponse<String> get(String url, String... headers) throws Throwable {
        URL realurl = null;
        InputStream in = null;
        HttpURLConnection conn = null;
        HttpResponse httpResponse = null;

        Map<String, String> header = new HashMap<>();
        for (int i = 0; i < headers.length; i = i + 2) {
            header.put(headers[i], headers[i + 1]);
        }
        realurl = new URL(url);
        conn = (HttpURLConnection) realurl.openConnection();
        conn.setConnectTimeout(8000);// 8秒
        conn.setReadTimeout(8000);// 8秒
        conn.setUseCaches(false);//不能使用缓存
        conn.setRequestMethod("GET");
        for (String key : header.keySet()) {
            conn.setRequestProperty(key, header.get(key));
        }
        httpResponse = new HttpResponse();
        httpResponse.responseCode = conn.getResponseCode();
        httpResponse.responseMessage = conn.getResponseMessage();
        httpResponse.headerFields = conn.getHeaderFields();
        in = conn.getInputStream();
        httpResponse.responseBody = streamToString(in);
        return httpResponse;
    }


    public static byte[] streamToBytes(InputStream in) {
        if (in == null) {
            return null;
        }
        byte[] bytes = null;
        BufferedInputStream bin = new BufferedInputStream(in);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        byte[] buffer = new byte[1028 * 8];
        int length = 0;
        try {
            while ((length = bin.read(buffer)) > 0) {
                bos.write(buffer, 0, length);
            }
            bos.flush();
            bytes = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bytes;
        }
    }

    public static String streamToString(InputStream in) {
        if (in == null) {
            return null;
        }
        InputStreamReader bin = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(bin);
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return sb.toString();
        }
    }

}
